import { createRouter, createWebHashHistory } from 'vue-router'
import AppLayout from '../views/AppLayout.vue'
import AppLogin from '../views/AppLogin.vue'
import RouteConfig from './config'
import { useRouterStore } from '../store/useRouterStore'
import { useUserStore } from '../store/useUserStore'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const routes = [
  {
    path: '/login',
    name: 'login',
    component: AppLogin
  },
  {
    path: '/layout',
    name: 'layout',
    component: AppLayout
  },
 
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由前置守卫
router.beforeEach((to, from, next) => {

  // 开启进度条

  NProgress.start()





  const { user } = useUserStore()
  const { isGetterRouter } = useRouterStore()
  if (to.path === '/login') {
    next()
  } else if (!user.role) {
    // 未授权
    next({
      path: '/login'
    })
  } else {
    // 已授权
    if (!isGetterRouter) {
      router.removeRoute('layout')
      configRouter()
      next({
        path: to.fullPath
      })
    }else{
    next()
  }
  }
})

router.afterEach(()=>{
  // 关闭进度条
  NProgress.done()
})

const configRouter = () => {
    // 在每次登录之前再次加上layout
    router.addRoute({
      path:'/layout',
      name:'layout',
      component:AppLayout
    })


  const checkPermission = (itemPath) => {
    const { user } = useUserStore()
    return user.role.rights.includes(itemPath) //判断登录角色里的路径是否包含当前itemPath
  }



  let { changeRouter } = useRouterStore()

  RouteConfig.forEach(item => {
    // 每一次都会执行这个方法  太浪费内存
    // console.log(item);
    checkPermission(item.path) && router.addRoute('layout', item)
    changeRouter(true)
  })
  router.addRoute('layout', {
    path: '/',
    redirect: '/index'
  })

  // 检查权限
  router.addRoute('layout',{
    path: '/:pathMatch(.*)*',//正则表达式。匹配任意字符 
    name: 'not found',
    component: () => import('../views/AppLayout404.vue')
  })
  
}
export default router